package com.yoofn.framework.http

import android.text.TextUtils
import com.yanzhenjie.nohttp.rest.Response
import com.yanzhenjie.nohttp.rest.StringRequest
import com.yoofn.framework.config.HttpConfig
import com.yoofn.framework.util.SPUtils

/**
 * Created by kalshen on 17/6/3.
 * @描述 noHttp的网络请求封装对象(携带token)
 */
class HttpTokenNetData : HttpNetData {

    constructor(what: Int, request: StringRequest) : super(what, request)

    /**
     * 当前请求是否开启token
     */
    //    var isEnableToken: Boolean = true

    /**
     * 同步本地token
     */
    fun syncLocalToken(response: Response<String>?) {

        val tokenList = response?.headers?.getValues(HttpConfig.TOKEN)
        if (tokenList?.isNotEmpty() ?: false) {
            //将response header 中的token缓存到本地
            tokenList?.let { SPUtils.getInstance().put(HttpConfig.TOKEN, it[0]) }
        }
    }


    /**
     * 统一添加请求头,如：token
     */
    fun addToken() {
        //统一处理token
        val token = SPUtils.getInstance().getString(HttpConfig.TOKEN)
        if (TextUtils.isEmpty(token)) {
            //本地token为空
            onTokenEmpty()
        } else {
            //添加token请求头
            request.setHeader(HttpConfig.TOKEN, token)
        }
    }

    /**
     * token为空的回调
     */
    fun onTokenEmpty() {
        //TODO token为空的回调
    }

}
